<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table border style="margin-top: 20px" :data="attrList">
          <el-table-column
            label="序号"
            width="80"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                v-for="item in row.attrValueList"
                style="margin: 0 2px"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #="{ row, $index }">
              <el-button
                size="small"
                type="primary"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>

              <el-popconfirm
                :title="`你确定要删除${row.attrName}?`"
                @confirm="removeAttr(row.id)"
                width="220px"
              >
                <template #reference>
                  <el-button
                    size="small"
                    type="primary"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button type="primary" @click="cancelHandler">取消</el-button>
        <el-table
          border
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                @blur="toLook(row)"
                ref="myInput"
              />
              <div v-else @click="toEdit(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveHandler">保存</el-button>
        <el-button type="primary" @click="cancelHandler">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
//引入分类小仓库
import useCategoryStore from "@/store/modules/category";
//引入API
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from "@/api/product/attr";
//引入ts数据类型
import type { AttrData, AttrValueList } from "@/api/product/attr/type";
import { defineOptions } from "vue";
import { ElMessage } from "element-plus";
defineOptions({
  name: "Attr",
});
//应用分类小仓库
let categoryStore = useCategoryStore();
let attrList = ref<AttrData[]>([]); //储存已有属性与属性值的数组
let scene = ref(0); //场景切换的变量
let myInput = ref(); //获取el-input元素 用户聚焦
//收集新增属性的数据
let attrParams = reactive<AttrData>({
  attrName: "", //已有属性的名字
  categoryId: "", //已有属性归属于那个三级分类
  categoryLevel: 3, //几层分类
  attrValueList: [], //新增属性值数组
});
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上一次属性与属性值的数据
    attrList.value = [];
    if (!categoryStore.c3Id) return;
    getAttrValueList();
  }
);
//获取已有属性的回调
const getAttrValueList = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrList.value = result.data;
  }
};
//添加属性
const addAttr = () => {
  //清除数据
  Object.assign(attrParams, {
    id: "",
    attrName: "", //已有属性的名字
    categoryId: categoryStore.c3Id, //已有属性归属于那个三级分类
    categoryLevel: 3, //几层分类
    attrValueList: [], //新增属性值数组
  });
  scene.value = 1;
};
//添加属性值回调
const addAttrValue = () => {
  //收集数据
  attrParams.attrValueList.push({
    valueName: "",
    flag: true, //用户属性值输入框的切换模式
  });
  nextTick(() => {
    myInput.value.focus();
  });
};
//修改属性
const updateAttr = (row: AttrValueList) => {
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
  scene.value = 1;
};
//输入框变为div模式
const toLook = (row: AttrValueList) => {
  //内容不能为空
  if (row.valueName.trim() == "") {
    ElMessage({
      type: "error",
      message: "内容不能为空",
    });
    return false;
  }
  //内容不能重复
  let repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "内容不能重复",
    });
    return false;
  }
  row.flag = false;
  return true;
};
//div变为输入框模式
const toEdit = (row: AttrValueList) => {
  row.flag = true;
  //自动聚焦
  nextTick(() => {
    myInput.value.focus();
  });
};
//保存回调函数
const saveHandler = async () => {
  //attrParmas.attrValueList.find查找是否满足条件，
  //如果是undefined说明没找到,否则找到了不符合条件的属性值
  const foundItem = attrParams.attrValueList.find((item) => !toLook(item));
  // console.log(foundItem);
  if (foundItem != undefined) return;
  let result = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    //切换场景
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    getAttrValueList();
  } else {
    //切换场景
    scene.value = 0;
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};
//取消回调函数
const cancelHandler = () => {
  scene.value = 0;
};
//删除某个属性的回答
const removeAttr = async (id: number | number) => {
  let result = await reqRemoveAttr(id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttrValueList();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
//路由组件销毁时:重置仓库中的数据
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped lang="scss"></style>
